package br.com.winesys.geta.databinding.component.editor;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JFormattedTextField;
import javax.swing.SwingConstants;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;

public class NumberEditor extends JFormattedTextField {

    protected NumberFormat numberFormat;

    public NumberEditor() {
        super();
        this.setValue(null);
        this.setHorizontalAlignment(SwingConstants.RIGHT);
        this.addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent evt) {
				if (!evt.isTemporary()){
					NumberEditor.this.selectAll();
				}
			}
		});
    }

    public NumberEditor(String format) {
        super();
        this.setFormat(format);
    }

    public NumberEditor(NumberFormat format) {
        super();
        this.setFormat(format);
    }

    public void setFormat(NumberFormat format) {
        this.numberFormat = format;
        NumberFormatter nf = new NumberFormatter(this.numberFormat);
        setFormatterFactory(new DefaultFormatterFactory(nf, nf, nf));
    }

    public void setFormat(String format) {
        this.numberFormat = new DecimalFormat(format);
        NumberFormatter nf = new NumberFormatter(this.numberFormat);
        setFormatterFactory(new DefaultFormatterFactory(nf, nf, nf));
    }

    @Override
    public void setValue(Object value) {
        try {
            setText(this.numberFormat.format(value));
        } catch (Exception ex) {
            setText("");
        }
    }
}
